package com.liuceng.zen.service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.liuceng.zen.constants.Constants;
import com.liuceng.zen.lib.upyun.UpYun;
import com.liuceng.zen.mapper.ImageMapper;
import com.liuceng.zen.pojo.domain.Image;
import com.liuceng.zen.pojo.form.ImageForm;
import com.liuceng.zen.web.auth.utils.RandomUtils;

@Service
public class ImageService extends BaseService<Image> {
  private final Logger logger = Logger.getLogger(ImageService.class);
  @Value("${upyun.bucketname}")
  private String bucketname;
  @Value("${upyun.username}")
  private String username;
  @Value("${upyun.password}")
  private String password;
  @Value("${upyun.imgurl}")
  private String imgurl;

  @Autowired
  private ImageMapper imageMapper;



  /**
   * @param fileContent
   * @param imageType
   * @param userId
   * @param wxUserId
   * @param imgFormat
   * @return
   */
  public Map<String, String> saveImage(byte[] imageByteData, int memberId, ImageForm form)
      throws IOException {
    Map<String, String> result = new HashMap<String, String>();
    result.put("result", Constants.ERR);
    String accessUrl = "/" + memberId + "/" + System.currentTimeMillis()
        + RandomUtils.genRandomStr(10) + "." + form.getImgFormat();
    UpYun upyun = new UpYun(bucketname, username, password);
    Map<String, String> params = new HashMap<String, String>();


    params.put("fix_width_or_height", form.getImgWidth() + "x" + form.getImgHeight());
    boolean isSuccess = upyun.writeFile(accessUrl, imageByteData, true, params);
    if (isSuccess) {
      result.put("result", Constants.OK);
      Image image = new Image();
      // 获取图片大小、尺寸 inser into db
      image.setModule(form.getImgType());
      image.setHeight(form.getImgHeight());
      image.setWidth(form.getImgWidth());
      image.setPath(imgurl + accessUrl + "_" + form.getImgWidth() + "x" + form.getImgHeight());
      image.setOriginalPath(imgurl + accessUrl);
      image.setExt(form.getImgFormat());
      image.setMemberId(memberId);
      image.setCreatedAt(new Date());
      image.setUpdatedAt(new Date());
      imageMapper.insertSelective(image);
      result.put("result", Constants.OK);
      result.put("accessUrl", accessUrl);
      result.put("picSavePath",
          imgurl + accessUrl + "_" + form.getImgWidth() + "x" + form.getImgHeight());
      result.put("picOrignalPath", imgurl + accessUrl);
    }
    return result;
  }

  public Image selectImageByMemberId(Integer memberId) {
    return imageMapper.selectByMemberId(memberId);
  }
}
